package com.example.mqdemo.returnlistener;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 必须是exchange没绑定队列
 * 而不是路由键不匹配的那种，不然收不到return消息
 */
public class SendProducer {

    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("localhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {


            channel.exchangeDeclare(EXCHANGE_NAME, "topic");

            /**
             * 这个路由不到*.ckl的队列
             * .ckl 可以路由
             * aaa.ckl 可以路由
             */
            String routingKey = "aaaaa";
            String message = "hello ,come on";

            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().deliveryMode(2).
                    contentEncoding("UTF-8").build();

            channel.basicPublish(EXCHANGE_NAME, routingKey,true, properties, message.getBytes("UTF-8"));
            channel.addReturnListener(new ReturnListener() {

                @Override
                public void handleReturn(int replyCode,
                                         String replyText,
                                         String exchange,
                                         String routingKey,
                                         AMQP.BasicProperties properties,
                                         byte[] body) {
                    System.out.println("=========handleReturn===method============");
                    System.out.println("replyText:"+replyText);
                    System.out.println("exchange:"+exchange);
                    System.out.println("routingKey:"+routingKey);
                    System.out.println("message:"+new String(body));
                }
            });

            System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
